package com.mikgonz.farkle;

import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.util.Log;

public class NetworkTask extends AsyncTask<Map<String, String>, Void, String> {

	public static final String REQUEST_TYPE = "request";
	public static final String POST = "post";
	public static final String GET = "get";
	public static final String DELETE = "delete";
	public static final String URI = "uri";

	private String scheme;

	public NetworkTask(String scheme) {
		super();
		this.scheme = scheme;
	}

	@Override
	protected String doInBackground(Map<String, String>... arg0) {

		Map<String, String> requestMap = arg0[0];
		HttpRequest req = null;

		String requestType = requestMap.get(REQUEST_TYPE);
		String uri = requestMap.get(URI);

		if (requestType.equals(POST))
			req = new HttpPost(uri);
		else if (requestType.equals(GET))
			req = new HttpGet(uri);
		else if (requestType.equals(DELETE))
			req = new HttpDelete(uri);
		
		Log.w(getClass().getName(),"Chose the request: " + requestType);
		try {

			Map<String, String> headerMap = arg0[1];
			
			Log.w(getClass().getName(),"Adding headers");
			for (Map.Entry<String, String> entry : headerMap.entrySet()) {

				Log.w(getClass().getName(),"Added - " + entry.getKey() + ":" + entry.getValue());
				req.addHeader(entry.getKey(), entry.getValue());

			}

			HttpHost targetHost = new HttpHost("farkle-server.appspot.com", -1,
					scheme);

			HttpResponse response = new DefaultHttpClient().execute(targetHost,
					req, new BasicHttpContext());

			HttpEntity entity = response.getEntity();
			String content = EntityUtils.toString(entity);

			return content;

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(getClass().getName(), "Error: " + e.getMessage());
			return "fail";
		}

	}

}
